package com.flyan.game.motafx.component;

import com.almasb.fxgl.entity.Entity;
import com.almasb.fxgl.entity.component.Component;
import com.flyan.game.motafx.component.character.BraveComponent;
import com.flyan.game.motafx.component.monster.MonsterComponent;
import com.flyan.game.motafx.core.algorithm.BattleAlgorithm;
import com.flyan.game.motafx.core.algorithm.BattleResult;
import com.flyan.game.motafx.core.algorithm.Battler;

/**
 * 战斗组件
 *
 * @author flyan
 * @version 1.0
 * @email flyan_by_chenu@sina.com
 * @since 2025/2/5
 */
public class BattleComponent extends Component {

    /**
     * 战斗中
     */
    protected boolean attacking;

    public BattleComponent() {

    }

    public BattleComponent setAttacking(boolean attacking) {
        this.attacking = attacking;
        return this;
    }

    public boolean isAttacking() {
        return attacking;
    }

    public void battle(Entity enemy, boolean attacker) {
        if (!enemy.hasComponent(BattleComponent.class)) {
            return;
        }

        /* 记录战斗状态 */
        setAttacking(true);
        enemy.getComponent(BattleComponent.class).setAttacking(true);

        var selfBattler = new Battler(entity);
        var enemyBattler = new Battler(enemy);
        BattleAlgorithm battleAlgorithm;
        if (attacker) {
            battleAlgorithm = new BattleAlgorithm(selfBattler, enemyBattler);
        } else {
            battleAlgorithm = new BattleAlgorithm(enemyBattler, selfBattler);
        }

        /* 模拟战斗，若可战斗，生效此次战斗影响 */
        BattleResult attackResult = battleAlgorithm.getBattleResult();
        if (attackResult.isCanBatter()) {
            attackResult.effect();
        }
    }

    public void attack(Entity enemy) {
        battle(enemy, true);
    }

    public void defend(Entity enemy) {
        battle(enemy, false);
    }

}
